package com.fashion.web.actions.tagcloud;

import com.fashion.model.Administrator;
import com.fashion.model.TagWord;
import com.fashion.service.TagWordService;
import com.fashion.utils.ConstItem;
import com.fashion.utils.GeneralResult;
import com.fashion.utils.StringUtils;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * User: gnyk
 * Date: 13-4-11
 */

@Scope("prototype")
@Controller
@Namespace("/tagcloud")
@ParentPackage("json-default")
public class TagCloudAction extends ActionSupport implements SessionAware, ServletRequestAware {
    private Map<String, Object> session;
    private HttpServletRequest request;

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    private TagWordService tagWordService;
    private Map<String, Object> dataGridView;
    private String name;
    private int page;
    private int rows;
    private GeneralResult result;
    private String id;
    private TagWord tagWordForm;
    private List<TagWord> tagWordList;
    private String jsonResult;
    private static final Logger logger = Logger.getLogger(TagCloudAction.class);

    @Action(value = "index", results = {@Result(name = SUCCESS, location = "tag_canvas.jsp")})
    public String tagCloud() throws Exception {
        tagWordList = tagWordService.searchTagWords("", 1, 10);
        tagWordService.encodeWithGB(tagWordList);

        return SUCCESS;
    }

    //refreshTagWordHtml

    @Action(value = "cloudIndex", results = {@Result(name = SUCCESS, location = "tag_index.jsp")})
    public String cloudIndex() throws Exception {

        return SUCCESS;
    }

    @Action(value = "refreshTagWordHtml", results = {@Result(name = SUCCESS, type = "json", params = {"root", "result"})})
    public String refreshTagWordHtml() throws Exception {
        result = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            result.setSuccessful(false);
            result.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        String serverName = request.getServerName();
        int port = request.getServerPort();
        StringBuilder urlPrefixBuilder = new StringBuilder("http://").append(serverName);
        if (port != 80) {
            urlPrefixBuilder.append(":").append(port);
        }

        String url = urlPrefixBuilder.append(StringUtils.TagCloudHtmlUrl).toString();

        try {
            tagWordService.refreshTagWordHtml(ServletActionContext.getServletContext().getRealPath(StringUtils.Persistent_Html_Folder), url);

            result.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in refreshTagWordHtml", e);
            result.setSuccessful(false);
            result.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "deleteTagWord", results = {@Result(name = SUCCESS, type = "json", params = {"root", "result"})})
    public String deleteTagWord() throws Exception {
        result = new GeneralResult();
        Administrator author = (Administrator) session.get(ConstItem.USER_OBJECT_IN_SESSION);

        if (null == author) {
            result.setSuccessful(false);
            result.setErrorMessage("No user logged in!");

            return SUCCESS;
        }

        try {
            tagWordService.deleteEntityById(id);

            result.setSuccessful(true);
        } catch (Exception e) {
            logger.error("Exception in delete tagWord with id: " + id, e);
            result.setSuccessful(false);
            result.setErrorMessage(e.getMessage());
        }

        return SUCCESS;
    }

    @Action(value = "fetchTagWordList", results = {@Result(name = SUCCESS, type = "json", params = {"root", "dataGridView"})})
    public String fetchTagWordList() throws Exception {
        List<TagWord> newses = tagWordService.searchTagWords(name, page, rows);
        int newsCount = tagWordService.countTagWords(name);

        dataGridView = new HashMap<String, Object>();
        dataGridView.put("rows", newses);
        dataGridView.put("total", newsCount);

        return SUCCESS;
    }

    @Action(value = "tagWordForm", results = {@Result(name = SUCCESS, location = "../form_result.jsp")})
    public String tagWordForm() throws Exception {
        result = new GeneralResult();

        List<TagWord> savedTagWords = tagWordService.loadAllWords();

        String word = tagWordForm.getWord().trim();
        tagWordForm.setWord(word);
        String id = tagWordForm.getId();
        for (TagWord tagWord : savedTagWords) {
            String savedWord = tagWord.getWord();
            String wordId = tagWord.getId();
            if (savedWord.equalsIgnoreCase(word) && !wordId.equals(id)) {
                result.setSuccessful(false);
                result.setErrorMessage("已有相同的标签存在！");

                JSONObject jsonObject = JSONObject.fromObject(result);
                jsonResult = jsonObject.toString();

                return SUCCESS;
            }
        }

        if (StringUtils.isNullOrEmpty(id)) {
            tagWordForm.setId(StringUtils.createTimeStamp());
            tagWordForm.setCreateDate(new Date());
            result.setEdit(false);
        } else {
            result.setEdit(true);
        }

        tagWordService.saveOrUpdate(tagWordForm);
        result.setSuccessful(true);

        JSONObject jsonObject = JSONObject.fromObject(result);
        jsonResult = jsonObject.toString();

        return SUCCESS;
    }


    @Resource
    public void setTagWordService(TagWordService tagWordService) {
        this.tagWordService = tagWordService;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, Object> getDataGridView() {
        return dataGridView;
    }

    public void setDataGridView(Map<String, Object> dataGridView) {
        this.dataGridView = dataGridView;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public GeneralResult getResult() {
        return result;
    }

    public void setResult(GeneralResult result) {
        this.result = result;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public TagWord getTagWordForm() {
        return tagWordForm;
    }

    public void setTagWordForm(TagWord tagWordForm) {
        this.tagWordForm = tagWordForm;
    }

    public List<TagWord> getTagWordList() {
        return tagWordList;
    }

    public void setTagWordList(List<TagWord> tagWordList) {
        this.tagWordList = tagWordList;
    }

    public String getJsonResult() {
        return jsonResult;
    }

    public void setJsonResult(String jsonResult) {
        this.jsonResult = jsonResult;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
}
